<template>
  <view class="chat-wrapper">
    <view class="header">历史会话</view>
    <view
      v-for="item in chatList"
      :key="item.id"
      class="chat-item"
      @tap="goToChat(item.id)"
    >
      <view class="chat-title">对话 ID：{{ item.id }}</view>
      <view class="chat-preview">{{ item.lastMessage || '（暂无内容）' }}</view>
    </view>
    <view class="new-chat" @tap="goToChat(null)">+ 新建会话</view>
  </view>
</template>

<script>
import { getChatIds, getChatHistory } from '../../service/api.js';

export default {
  data() {
    return {
      type: '',
      chatList: []
    };
  },
  onLoad(options) {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
      return;
    }
    
    this.type = options.type;
    this.loadChats();
  },
  onShow() {
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({ url: '/pages/login/index' });
    }
  },
  methods: {
    // chatList页面 loadChats 修改如下
    async loadChats() {
      const idsRes = await getChatIds(this.type);
      const ids = idsRes.data || [];
    
      const chatList = await Promise.all(
        ids.map(async id => {
          const res = await getChatHistory(this.type, id);
          const messages = res.data || [];
          const last = messages[messages.length - 1];
          const lastMessage = last?.message || last?.content || '（暂无内容）';
          return {
            id,
            lastMessage
          };
        })
      );
    
      this.chatList = chatList;
    },
    goToChat(chatId) {
      uni.navigateTo({
        url: `/pages/ai/chat?type=${this.type}&chatId=${chatId || ''}`
      });
    }
  }
};
</script>

<style>
.chat-wrapper {
  background: #f3f6ff;
  padding: 30rpx;
}
.header {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}
.chat-item {
  background-color: white;
  padding: 20rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}
.chat-title {
  font-size: 30rpx;
  font-weight: bold;
}
.chat-preview {
  font-size: 26rpx;
  color: #666;
  margin-top: 10rpx;
}
.new-chat {
  background: #5983ff;
  color: white;
  padding: 20rpx;
  text-align: center;
  border-radius: 10rpx;
  font-size: 32rpx;
}
</style>
